package com.weiyuwqj.admin.controller.admin.item;

import com.weiyuwqj.admin.controller.admin.log.annotation.LogAnnotation;
import com.weiyuwqj.api.common.Paginator;
import com.weiyuwqj.api.constant.ItemStatus;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.model.BasItem;
import com.weiyuwqj.api.model.BasUser;
import com.weiyuwqj.api.model.BusAccount;
import com.weiyuwqj.api.model.BusItemInvest;
import com.weiyuwqj.api.model.BusVerify;
import com.weiyuwqj.api.model.convert.InvestTypeConvert;
import com.weiyuwqj.api.model.convert.ItemAddtimeConvert;
import com.weiyuwqj.api.model.convert.ItemCycleConvert;
import com.weiyuwqj.api.model.convert.ItemRateConvert;
import com.weiyuwqj.api.model.convert.ItemRepayMethodConvert;
import com.weiyuwqj.api.model.convert.ItemStatusConvert;
import com.weiyuwqj.api.model.convert.ItemTypeConvert;
import com.weiyuwqj.api.model.convert.ModelConvert;
import com.weiyuwqj.api.model.vo.BasItemVo;
import com.weiyuwqj.api.model.vo.BusItemInvestVo;
import com.weiyuwqj.api.service.BasItemPrepaymentService;
import com.weiyuwqj.api.service.BasItemService;
import com.weiyuwqj.api.service.BasUserService;
import com.weiyuwqj.api.service.BusAccountService;
import com.weiyuwqj.api.service.BusInvestService;
import com.weiyuwqj.api.service.BusVerifyLogService;
import com.weiyuwqj.api.service.SysPictureService;
import com.weiyuwqj.api.service.SysUserService;
import com.weiyuwqj.api.util.ExcelUtils;
import com.weiyuwqj.api.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyong on 2016/8/5.
 */
@Controller
@RequestMapping("/admin/item")
public class ItemController {

    @Autowired
    private BasItemService itemService;
    @Autowired
    private SysPictureService pictureService;
    @Autowired
    private BusVerifyLogService verifyLogService;
    @Autowired
    private BusInvestService investService;
    @Autowired
    private BasItemPrepaymentService itemPrepaymentService;
    @Autowired
    private BasUserService userService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private BusAccountService accountService;

    //项目列表接口
    @ResponseBody
    @RequestMapping("/getList")
    public Object getList(Paginator p, String itemName, String itemType, String itemStatus, String beginDate, String endDate,
                          String item, String realname,String itemRepayMethod) {
        Map map = new HashMap();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(itemType)) {
            map.put("itemType", itemType);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(itemName)) {
            map.put("itemName", itemName);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(item)) {
            map.put("item", item);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(itemStatus)) {
            map.put("itemStatus", itemStatus);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(beginDate)) {
            map.put("beginDate", beginDate);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(endDate)) {
            map.put("endDate", endDate);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(realname)) {
            map.put("realname", realname);
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(itemRepayMethod)) {
            map.put("itemRepayMethod", itemRepayMethod);
        }
        return itemService.getList(p, map);
    }



//    /**
//     * 初审项目
//     *
//     * @param itemId
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "/firstVerify", method = RequestMethod.POST)
//    @LogAnnotation(module = "项目管理/项目初审", description = "初审")
//    public Object firstVerify(Integer itemId, String firstVerifyContent, Integer firstVerifyStatus, Integer countdown, String releaseTime) {
//        BusVerify verify = new BusVerify();
//        verify.setSourceUserId(1);
//        verify.setVerifyContent(firstVerifyContent);
//        verify.setVerifyStatus(firstVerifyStatus.byteValue());
//        verify.setVerifyUserId(2);
//        verify.setVerifyType((byte) 2);
//        return itemService.firstVerify(itemId, verify, countdown, releaseTime,1);
//    }

//    /**
//     * 复审项目
//     *
//     * @param itemId
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "/fullVerify", method = RequestMethod.POST)
//    @LogAnnotation(module = "项目管理/项目复审", description = "复审")
//    public Object fullVerify(Integer itemId, String fullVerifyContent, Integer fullVerifyStatus) {
//        BusVerify verify = new BusVerify();
//        verify.setSourceUserId(1);
//        verify.setVerifyContent(fullVerifyContent);
//        verify.setVerifyStatus(fullVerifyStatus.byteValue());
//        verify.setVerifyUserId(2);
//        verify.setVerifyType((byte) 2);
//
//        //复审动作
//        BasItem item = itemService.selectByKey(itemId);
//        if (item.getItemStatus() != ItemStatus.FULL_COMPLETE && item.getItemStatus() != ItemStatus.INTERCEPT_COMPLETE) {
//            throw new CrowdException("item.status.not_full_complete");
//        }
//        //失败撤回
//        if (verify.getVerifyStatus() == 2) { // 审核结果
//            return itemService.cancel(itemId);
//        } else {
//            List<BusItemInvest> investList = investService.getInvestListByItemId(itemId);
//            //解冻
//            if (item.getFullStatus() == 0) {
//                itemService.thawBoolean(investList, itemId);
//            }
//            //批量投资
//            BasItem batchInvestItem = itemService.selectByKey(itemId);
//            if (batchInvestItem.getFullStatus() == 1) {
//                Map batchInvestMap = itemService.batchInvest(item, investList);
//                if ("fail".equals(batchInvestMap.get("result"))) {
//                    return batchInvestMap;
//                }
//            }
//            //成标
//            BasItem creatItem = itemService.selectByKey(itemId);
//            if (creatItem.getFullStatus() == 2) {
//                itemService.creatBid(itemId, item, investList);
//            }
//        }
//        return Message.OK;
//    }

//    /**
//     * 项目撤回
//     */
//    @ResponseBody
//    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
//    @LogAnnotation(module = "项目管理/项目撤回", description = "撤回")
//    public Object doCancel(Integer id) {
//        return itemService.cancel(id);
//    }

    //查询项目信息
    @ResponseBody
    @RequestMapping(value = "/getOneById", method = RequestMethod.POST)
    public Object getOne(Integer id) {
        Map param = new HashMap();
        param.put("itemId", id);

        Map map = new HashMap();
        //项目信息
        BasItem item = itemService.selectByKey(id);
        BasUser user = userService.selectByKey(item.getItemUserId());

        map.put("item", item);
        map.put("itemPrepayment", itemPrepaymentService.getOneByItemId(id));
        if(user !=null){
            map.put("loanUser", user.getUsername());
        }
        if (item.getGuaranteeId() != null && item.getGuaranteeId() != 0) {
            map.put("guaranteeUser", sysUserService.selectByKey(item.getGuaranteeId()).getSysUserName());
        }
        map.put("pictureList", pictureService.getPictureByItemId(param));
        map.put("time", verifyLogService.getListByItemId(id));
//        param.put("pictureType",6);
//        map.put("picture",pictureService.getPictureByItemId(param));
        return map;
    }

    //查询投资信息
    @ResponseBody
    @RequestMapping(value = "/getItemInvestByItemId", method = RequestMethod.POST)
    public Object getItemInvestByItemId(Paginator p, Integer id) {
        Map map = new HashMap();
        map.put("itemId", id);
        return investService.getList(p, map);
    }


    //导出投资信息
    @ResponseBody
    @RequestMapping("/excel/invest")
    @LogAnnotation(module = "项目管理/项目查询", description = "导出投资信息")
    public Object excelInvest(HttpServletRequest request, Integer id) {
        String[] cArray = {"用户名", "投资金额", "应收总额", "应收本金", "应收利息", "投资类型", "投标时间"};
        String[] eArray = {"Username", "InvestAmount", "CollectAmount", "CollectPrincipal", "CollectInterest", "InvestType", "Addtime"};
        ModelConvert[] converts = {null, null, null, null, null, new InvestTypeConvert(), new ItemAddtimeConvert()};

        List<String> cList = Arrays.asList(cArray);
        List<String> eList = Arrays.asList(eArray);
        List<ModelConvert> convertList = Arrays.asList(converts);
        Map map = new HashMap();
        map.put("itemId", id);

        List<BusItemInvestVo> contentList = investService.listInvest(map);

        String serverDir = request.getServletContext().getRealPath("/") + "admin/export/";
        //String excelFilePath=ExcelUtils.export(allList,serverDir);
        String excelFilePath = ExcelUtils.export("用户投资记录", cList, eList, convertList, contentList, serverDir);

        HashMap ret = Message.OK;
        ret.put("file", "export/" + excelFilePath);
        return ret;
    }


    //项目相关统计
    @ResponseBody
    @RequestMapping(value = "/getCount", method = RequestMethod.POST)
    public Object getCount(String itemName, String itemType, String itemStatus, String beginDate, String endDate, String item) {
        Map map = new HashMap();
        map.put("itemName", itemName);
        map.put("item", item);
        if (StringUtils.isNull(itemType)) {
            map.put("itemType", null);
        } else {
            map.put("itemType", itemType);
        }
        if (StringUtils.isNull(itemStatus)) {
            map.put("itemStatus", null);
        } else {
            map.put("itemStatus", itemStatus);
        }
        map.put("beginDate", beginDate);
        map.put("endDate", endDate);
        Map param = new HashMap();
        param.put("AllItemNum", itemService.countByAllItemNum(map));
        param.put("FirstItemNum", itemService.countByFirstItemNum(map));
        param.put("NoRepayItemNum", itemService.countByNoRepayItem(map));
        param.put("RepayItemNum", itemService.countByRepayItem(map));
        param.put("AllItemAccount", itemService.sumByAllItemAccount(map));
        param.put("FirstItemAccount", itemService.sumByFirstItemAccount(map));
        param.put("itemInvestNum", itemService.countItemInvestNum(map));
        param.put("NoRepayItemAccount", itemService.sumNoRepayItemAccount(map));
        param.put("RepayItemAccount", itemService.sumRepayItemAccount(map));
        param.put("NoFullItemNum", itemService.sumNoFullItemNum(map));
        param.put("NoFullItemAccount", itemService.sumNoFullItemAccount(map));
        param.put("FullItemAccountBalance", itemService.sumFullItemAccountBalance(map));
        param.put("itemAutoInvestNum", itemService.countAutoInvestNum(map));
        param.put("itemNoAutoInvestNum", itemService.countNoAutoInvestNum(map));
        return param;
    }

    /**
     * 项目查询导出
     *
     * @param request
     * @param itemType
     * @param itemStatus
     * @param itemName
     * @param beginDate
     * @param endDate
     * @return
     */
    @ResponseBody
    @RequestMapping("/excel/item")
    @LogAnnotation(module = "项目管理/项目查询", description = "导出项目查询信息")
    public Object ItemExcel(HttpServletRequest request, String itemType, String itemStatus, String itemName, String beginDate, String endDate, String item) {

        String[] cArray = {"ID", "名称", "借款人", "担保人ID", "类型", "金额", "期限", "期限单位", "利率", "加息利率", "进度", "状态", "还款方式", "添加时间"};
        String[] eArray = {"Id", "ItemName", "Realname", "GuaranteeId", "ItemType", "ItemAccount", "ItemCycle", "ItemCycleUnit",
                "ItemRate", "ItemAddRate", "ItemScale", "ItemStatus", "ItemRepayMethod", "Addtime"};
        ModelConvert[] converts = {null, null, null, null, new ItemTypeConvert(),
                null, null, new ItemCycleConvert(), new ItemRateConvert(), new ItemRateConvert(), new ItemRateConvert(),
                new ItemStatusConvert(), new ItemRepayMethodConvert(), new ItemAddtimeConvert()};

        List<String> cList = Arrays.asList(cArray);
        List<String> eList = Arrays.asList(eArray);
        List<ModelConvert> convertList = Arrays.asList(converts);
        Map map = new HashMap();
        map.put("itemName", itemName);
        map.put("item", item);
        map.put("itemType", itemType);
        map.put("itemStatus", itemStatus);
        map.put("beginDate", beginDate);
        map.put("endDate", endDate);
        List<BasItemVo> contentList = itemService.getList(map);

        String serverDir = request.getServletContext().getRealPath("/") + "admin/export/";
        String excelFilePath = ExcelUtils.export("项目管理", cList, eList, convertList, contentList, serverDir);

        HashMap ret = new HashMap();
        ret.put("result", "success");
        ret.put("file", "export/" + excelFilePath);
        return ret;
    }


    //项目截标
    @ResponseBody
    @RequestMapping("/interceptItem")
    @LogAnnotation(module = "项目管理/项目截标", description = "截标")
    public Object interceptItem(Integer itemId) {
        itemService.interceptItem(itemId);
        return Message.OK;
    }



    //根据id修改项目内容
    @ResponseBody
    @RequestMapping("/modifyContentById")
    @LogAnnotation(module = "项目管理/项目查询", description = "根据id修改项目内容")
    public Object modifyContentById(String itemContent, Integer id) {
        itemService.modifyContentById(itemContent, id);
        return Message.OK;
    }

//    /**
//     * 扫标
//     *
//     * @param userId 用户ID
//     * @param itemId 项目ID
//     * @return 扫标结果
//     */
//    @ResponseBody
//    @RequestMapping(value = "/useEnterpriseRecharege", method = RequestMethod.POST)
//    public Object userEnterpriseRecharege(Integer userId, Integer itemId) {
//        BusAccount account = accountService.getBusAccountByUserId(userId); // 账户查询
//        BasItem item = itemService.selectByKey(itemId); // 标情况查询
//        BigDecimal subtract = item.getItemAccount().subtract(item.getItemOngoingAccount()); // 标剩余可投资金额
//        if (account.getUsable().compareTo(subtract) > 0) { // 账户可用余额大于标剩余可购买余额则进行投资
//            try {
//                return investService.doInvest(userId, subtract.doubleValue(), itemId, null, 1, null); // 投资
//            } catch (Exception e) {
//                e.printStackTrace();
//                Map<String, Object> resultMap = new HashMap<>();
//                resultMap.put("result", "fail");
//                resultMap.put("messageText", "项目投资出错");
//                return resultMap;
//            }
//        } else {
//            Map<String, Object> resultMap = new HashMap<>();
//            resultMap.put("result", "fail");
//            resultMap.put("messageText", "账户可用余额不足");
//            return resultMap;
//        }
//
//    }



}
